<template>
  <div class="qc_webchat_Quality">
    <affix :label="$t('webchat.sessionRecord')" :quality="true" @isFold="isFold"></affix>
    <div class="wrap_con" v-show="isShowCon">
      <el-form label-position="top" :inline="true" :model="chatForm" class="demo-form-inline">
        <el-form-item label="">
          <el-checkbox v-model="chatForm.skipQuality" @change="skipChange">{{$t('qualityCheck.showSkippedData')}}</el-checkbox>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="$t('public.createTime')+':'">
              <el-date-picker size="mini"
                v-model.trim="chatForm.createTime"
                :id="['c1','c2']"
                type="datetimerange"
                :picker-options="pickerOptions2"
                :placeholder="$t('public.timeRanges')"
                align="right"
                :editable="boolean"
                :clearable="false"
                @change=createTimeChange>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.agent')+':'">
            <el-popover
              ref="popover3"
              placement="bottom"
              @show="popoverWebchatShow"
              width="240"
              trigger="click">
              <agent-tree :readSeat="followedWebchatAgents" ref="agentTreeWebchat" @saveFollowedAgents="saveFollowedWebchatAgents"></agent-tree>
            </el-popover>
            <div class="follow-agent-wrap" v-popover:popover3>
                <span class="follow-agent follow-common" v-for="item in followedWebchatAgents" :key="item._id">{{item.label}}
                  <i class="el-icon-close" @click.stop="closeFollowedWebchatAgents(item._id)"></i>
                </span>
              <div>
                <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
              </div>
            </div>
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('webchat.endType')+':'">
              <el-cascader
                popper-class="webchat-finish"
                style="width: 100%"
                :options="closeOptions"
                filterable
                v-model.trim="activeFinish"
                change-on-select
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.satisfaction')+':'">
              <el-select size="mini" v-model.trim="chatForm.appraiseKey" filterable :placeholder="$t('public.all')">
                <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
                <el-option :label="'--'+$t('public.unevaluated')+'--'" value="unevaluated"></el-option>
                <el-option
                  v-for="(item, index) in appraiseList"
                  :label="item.name"
                  :value="item.key"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="$t('webchat.platformSource')+':'">
              <el-select size="mini" v-model.trim="chatForm.platform" :placeholder="$t('public.all')">
                <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
                <el-option
                  v-for="(item, index) in platforms"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('webchat.takeTime')+':'">
              <el-date-picker size="mini"
                              :id="['m1','m2']"
                              v-model.trim="chatForm.beginTime"
                              type="datetimerange"
                              :picker-options="pickerOptions2"
                              :placeholder="$t('public.timeRanges')"
                              :editable="false"
                              align="right"
                              style="margin-left: 0;"
                              @change=timeChange>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.queues')+':'">
              <el-select size="mini" v-model.trim="chatForm.toPeer" filterable :placeholder="$t('qualityCheck.skillGroupSearch')">
                <el-option
                  v-for="(item, index) in webchatQueueList"
                  :key="index"
                  :label="item.DisplayName"
                  :value="item.Exten">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('public.customerName')+':'">
              <el-input size="mini" v-model.trim="chatForm.sName" :placeholder="$t('public.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">    
          <!-- 会话ID -->
          <el-col :span="6">
            <el-form-item :label="$t('qualityCheck.sessionId')">
              <el-input size="mini" v-model.trim="chatForm._id" :placeholder="$t('public.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('webchat.msgNum')+':'">
              <el-radio-group v-model.trim="chatForm.msgCountType">
                <el-radio size="mini" label="gt" >{{$t('webchat.moreThan')}}</el-radio>
                <el-radio size="mini" label="lt" >{{$t('webchat.lessThan')}}</el-radio>
                <el-radio size="mini" label="eq" >{{$t('webchat.equal')}}</el-radio>
              </el-radio-group>
              <el-input style="margin-left:20px;width:90px;" size="mini" v-model.trim="chatForm.msgCount" :placeholder="$t('public.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="sub" style="margin-bottom: 28px">
      <el-button class="primary_btn" @click="rest">{{$t('public.reset')}}</el-button>
      <el-button type="primary" class="search primary_btn" @click="queryList">{{$t('public.search2')}}</el-button>
    </div>
    <!-- 在线咨询质检 -->
    <webchat-grade :ruleRender="ruleRender" :webchatDialogShow="webchatDialogShow" :currentItemWebchat="this.currentItemWebchat" v-if="webChatIsShow" @close="off" :currentItem = "this.currentItem" :currentGrade = "{}" @saveGrade="saveGrade" @nextGrade="nextGrade" @saveGradeAnd="saveGradeAnd"></webchat-grade>
    <big-image :imgInfo="bigImage" @closeImageDialog="closeBigImage"></big-image>
    <affix :label="$t('public.searchResult')"></affix>
    <div class="sub">
      <el-button class="primary_btn" type="primary" @click="QCcheck">{{$t('intelligentQualityCheck.intelligentQua')}}</el-button>
      <el-button class="primary_btn" @click="setHeaderConfig">{{$t('report.setHeaderConfig')}}</el-button>
    </div>
    <div class="wrapper_table">
      <div class="wrap_page clearfix">
        <div class="choose fl">
          <span>{{checked ? $t('intelligentQualityCheck.checkIntelligentAll'): $t('intelligentQualityCheck.checkIntelligentCount', {arrChooseTab: arrChooseTab.length})}}</span>
          <span @click="cancelChoose" class="not_choose" v-if="arrChooseTab.length">{{$t('intelligentQualityCheck.intelCancelChoose')}}</span>
          <el-checkbox v-model="checked" @change="checkAll">{{$t('public.checkAll')}}</el-checkbox>
        </div>
        <div class="search-pagination fr">
          <div :class="{page_mask:arrChooseTab.length}"></div>
          <pagination
                  :moreFlag="moreNorFlag"
                  :allCount="allCount"
                  :small="pagination.small"
                  :currentPage="pagination.currentPage"
                  :count="count"
                  :noJump="true"
                  @turnPage="turnPage"
                  :totalPage="totalPage"
                  @getAllCount="getAllCount"
                  >
          </pagination>
        </div>
      </div>
      <base-table @checkData="checkData" ref="qualityTable" :tableData="tableData" :options="tableDataHeader.Config" @grade="handle" @viewLook="look"></base-table>
    </div>
    <div class="looklog">
        <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :visible.sync="isShow" :title="title">
          <div class="tables">
          <div class="deploy">
            <div class="search-pagination">
              <pagination
                      :small="paginationRecord.small"
                      :currentPage="paginationRecord.currentPage"
                      :count="countRecord"
                      @turnPage="turnPageRecord"
                      :totalPage="totalPageRecord"
                      >
              </pagination>
            </div>
          </div>
          <el-table :data="recordList" size="mini">
            <el-table-column prop="user" :label="listenpp" width="">
            </el-table-column>
            <el-table-column prop="" label="" width="">
            </el-table-column>
            <el-table-column prop="time" :label="listenTime" width="">
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
    <!--配置表头-->
    <header-option v-show="isShowTableConfig" :show="isShowTableConfig" :option="headOptions" :type="tableConfigType" v-on:close="closeTableConfig"></header-option>
    <qc-dialog :dialogVisible="dialogVisible" :Qclists="Qclists" :dialogVisibleOne="dialogVisibleOne" @comitQc="comitQc" @closeQcDialog="closeQcDialog"></qc-dialog>
    <el-dialog
      title="执行智能质检"
      :visible.sync="dialogVisibleOne"
      width="30%"
      :close-on-click-modal="false"
      @close="closeQcDialog">
      <span>{{$t('intelligentQualityCheck.intelTaskCommit')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOne=false" class="primary_btn">{{$t('public.Iknow')}}</el-button>
        <el-button type="primary" @click="goQualityRes" class="primary_btn">{{$t('intelligentQualityCheck.intelAtOnceGo')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import Pagination from '@/components/public-modules/card/Pagination'
  import qcDialog from './qcDialog'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import AgentTree from '@/components/business-modules/qualityCheck/base/qualityAgentTree'
  import webchatGrade from './WebchatGrade'
  import {deepClone, getDateTime, scopeAgents, updateAllOptions, initFinishName, getFormatDateTime} from '@/utils/m7Utils.js'
  import headerOption from '../../report/base/headerOption.vue'
  import BaseTable from '../qualityTable/qualityTable.vue'
  import bus from '@/store/eventBus'
  import BigImage from '@/components/public-modules/bigImage/BigImage'
  export default {
    name: 'qc_webchat_Quality',
    data () {
      return {
        chatPages: 0,
        checked: false,
        boolean: false,
        Qclists: [],
        ruleRender: [],
        dialogVisible: false,
        dialogVisibleOne: false,
        currentItem: {},
        bigImage: {
          bigImageShow: false,
          url: ''
        },
        tableConfigType: 'quality_webchat_table_title',
        isShowTableConfig: false,
        arrChooseTab: [],
        webchatDialogShow: false,
        currentItemWebchat: {},
        webChatIsShow: false,
        moreNorFlag: false, // table翻页组件开始
        allCount: 0,
        pagination: {
          small: false,
          currentPage: 1
        },
        currentId: '', // 查看日志start
        title: '',
        countRecord: 0,
        listenTime: '',
        listenpp: '',
        headOptions: {},
        paginationRecord: {
          small: false,
          currentPage: 1
        },
        isShow: false,
        totalPageRecord: 1, // end
        recordList: [],
        tableData: [],
        isShowCon: false,
        qu: {},
        agentList: [],
        sessionOptions: [],
        closeOptions: [],
        finishReasonList: [],
        appraiseList: [],
        platforms: [
          {label: this.$t('webchat.websiteCon'), value: 'pc'},
          {label: this.$t('webchat.wapCon'), value: 'wap'},
          {label: this.$t('webchat.appCon'), value: 'sdk'},
          {label: this.$t('webchat.weChatCon'), value: 'weixin'},
          {label: this.$t('webchat.weChatMini'), value: 'wxmini'},
          {label: this.$t('webchat.weBoCon'), value: 'weibo'},
          {label: this.$t('webchat.enterpriseShot'), value: 'wxwork'},
          {label: this.$t('webchat.baiduBCP'), value: 'ocpc'},
          {label: this.$t('webchat.TikTok'), value: 'dy'},
          {label: this.$t('webchat.platformWXKF'), value: 'wxkf'}
        ],
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        tableDataHeader: {
          Config: [{ 'order': '1', 'name': 'CALL_NO_SHOW', 'displayname': '主叫号码', 'show': true }, { 'order': '2', 'name': 'DISPOSAL_AGENT', 'displayname': '接听座席', 'show': true }, { 'order': '3', 'name': 'CALLED_NO_SHOW', 'displayname': '被叫号码', 'show': true }, { 'order': '4', 'name': 'CONNECT_TYPE_show', 'displayname': '呼叫类型', 'show': true }, { 'order': '5', 'name': 'ERROR_MEMO', 'displayname': '呼入技能组', 'show': true }, { 'order': '6', 'name': 'INVESTIGATE', 'displayname': '满意度', 'show': true }, { 'order': '7', 'name': 'OFFERING_TIME', 'displayname': '呼叫时间', 'show': true }]
        },
        isSave: false,
        activeFinish: [],
        chatForm: {
          skipQuality: false,   //   获取被跳过的
          beginTime: '',
          createTime: '',
          finishKey: '',
          user: '',
          appraiseKey: '',
          msgCount: '',
          msgCountType: '',
          toPeer: '',    //  技能组
          platform: '',
          sName:'',//客户名称
          _id:''//会话ID
        },
        finishOptions: {},          //  在线结束会话类型列表
        webchatQueueList: [],
      }
    },
    props: {
      refreshNum: Number
    },
    methods: {
      //坐席选择
      popoverWebchatShow () {
        this.$refs.agentTreeWebchat.setCheckedKeys()
      },
      //坐席保存
      saveFollowedWebchatAgents (agents) {
        this.chatForm.user = deepClone(agents)
        document.getElementsByTagName('body')[0].click()
      },
      //坐席删除
      closeFollowedWebchatAgents (agent) {
        this.chatForm.user = this.chatForm.user.filter((item) => item !== agent)
      },
      // 全选逻辑
      checkAll (bool) {
        if (bool) {
          this.$refs.qualityTable.toggleSelection(this.tableData)
          this.arrChooseTab = ['1']
        } else {
          this.$refs.qualityTable.cancleChoose()
          this.arrChooseTab = []
        }
        this.checked = bool
      },
      // 跳过数据
      skipChange () {
        this.query()
      },
      // 跳转结果页
      goQualityRes () {
        this.closeQcDialog()
        this.$router.push({
          path: '/index/intelligentQualityCheck/quality_check_result',
          name: 'qualityCheckResult',
          params: {
            webOrCallOrTaskTemp: 2
          }
        })
      },
      // 提交智能质检
      comitQc (arr) {
        let data1 = {
          type: 'webchat',
          taskList: [],
          rule: arr
        }
        if (this.checked) {
          this.dialogVisible = false
          this.pagination.currentPage = 1
          this.chatForm.page = 1
          this.chatForm.morePage = 1
          this.chatForm.menuId = 'autoqc_query'
          if (this.chatForm.beginTime && this.chatForm.beginTime[0] !== null) {
            this.chatForm.beginTimeBegin = getDateTime(this.chatForm.beginTime[0])
          }
          if (this.chatForm.beginTime && this.chatForm.beginTime[1] !== null) {
            this.chatForm.beginTimeEnd = getDateTime(this.chatForm.beginTime[1])
          }
          if (this.chatForm.beginTimeEnd === '' && this.chatForm.beginTimeBegin === '') {
            this.chatForm.beginTime = ''
          }

          if (this.chatForm.createTime) {
          if (typeof this.chatForm.createTime[0] === 'object') {
            this.chatForm.createTimeBegin = getDateTime(this.chatForm.createTime[0])
          } else {
            this.chatForm.createTimeBegin = this.chatForm.createTime[0] || ''
          }
          if (typeof this.chatForm.createTime[1] === 'object') {
            this.chatForm.createTimeEnd = getDateTime(this.chatForm.createTime[1])
          } else {
            this.chatForm.createTimeEnd = this.chatForm.createTime[1] || ''
          }
        }
          this.chatForm.pageSize = 10
          let _qu = deepClone(this.chatForm)
          _qu.queryCount = true
          this.qu = _qu
          this.allCount = 0
          let data = deepClone(this.chatForm)
          delete data.beginTime
          delete data.createTime
          delete data.searchType
          data1.query = data
          this.$store.dispatch('addTask', data1).then((res) => {
            if (res.success) {
              this.dialogVisibleOne = true
              this.query()
              console.log(res)
            }
          })
          return
        }
        for (let i = 0; i < this.arrChooseTab.length; i++) {
          data1.taskList.push(this.arrChooseTab[i]._id)
        }
        this.$store.dispatch('addTask', data1).then((res) => {
          if (res.success) {
            this.dialogVisibleOne = true
            this.query()
            console.log(res)
          }
        })
      },
      closeQcDialog () {
        this.dialogVisible = false
        this.dialogVisibleOne = false
      },
      QCcheck () {
        if (!this.arrChooseTab.length && !this.checked) {
          this.$message.error(this.$t('intelligentQualityCheck.intelPleaChooseQc'))
          return
        }
        if (this.checked) {
          // 判断质检的条数
          let form = this.qu
          this.$store.dispatch('webchatSearch1', form).then((res) => {
            this.listNum = res.count
            if (this.listNum > 10000) {
              this.$message.error(this.$t('intelligentQualityCheck.intelMaxNum'))
              return
            } else if (this.listNum === 0) {
              this.$message.error(this.$t('intelligentQualityCheck.intelPleaChooseQc'))
              return
            } else {
              this.QcChechShow()
            }
          })
        } else {
          this.QcChechShow()
        }
      },
      // 满足质检条件之后展示
      QcChechShow () {
        this.Qclists = []
        let data1 = {
          isEnable: true
        }
        this.$store.dispatch('getRuleLessList', data1).then((res) => {
          if (res.success) {
            // 过滤下类型
            res.data = res.data.filter((item) => {
              return item.type === 'webchat'
            })
            for (var i = 0; i < res.data.length; i++) {
              this.Qclists.push({
                name: res.data[i].name,
                value: res.data[i]._id
              })
            }
          }
        })
        this.dialogVisible = true
      },
      // 跳过评分下一条
      nextGrade () {
        this.isSave = true
        let passId = this.tempList[this.currentIndex]._id
        this.$store.dispatch('skipQualitySession', {_id: passId})
        this.$store.commit('deleteGraded/qualityCheckAuto', this.currentIndex)
        this.$store.commit('deleteGraded/qualityCheckAuto', 1)
        if (this.tempList.length <= 0) {
          this.$message.success(this.$t('qualityCheck.allRatingFinish'))
          this.webchatDialogShow = false
          this.callDialogShow = false
          this.query()
        } else {
          this.$message.success(this.$t('qualityCheck.nextGrade'))
          this.handle(this.tempList[0])
        }
      },
      // 保存并评分下一条
      saveGradeAnd (data) {
        this.isSave = true
        this.$store.commit('deleteGraded/qualityCheckAuto', this.currentIndex)
        this.$store.dispatch('submitOneManulQcChat', data).then((res) => {
          if (res && res.success) {
            this.$message.success(this.$t('intelligentQualityCheck.intelGradeSuccess'))
            // 删除tempList评价完的那个
            this.$store.commit('deleteGraded/qualityCheckAuto', 1)
            // 判断是否还有没质检了
            if (this.tempList.length <= 0) {
              this.$message.success(this.$t('qualityCheck.allRatingFinish'))
              this.query()
            } else {
              this.$message.success(this.$t('qualityCheck.rateSuccessNext'))
              this.handle(this.tempList[0])
            }
          }
        })
      },
      // 保存评分
      saveGrade (data) {
        this.isSave = true
        this.$store.dispatch('submitOneManulQcChat', data).then((res) => {
          if (res && res.success) {
            this.query()
            this.webchatDialogShow = false
            this.$message.success(this.$t('intelligentQualityCheck.intelGradeSuccess'))
          }
        })
      },
      // 重置表单
      rest () {
        for (let i in this.chatForm) {
          if (i === 'createTime') {
            this.chatForm[i] = this.chatCreateTimeReset()
          } else {
            this.chatForm[i] = ''
          }
        }
        this.activeFinish = ''
      },
      chatCreateTimeReset () {
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let createStartTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 7)).split(' ')[0] + ' 00:00:00'
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        let createArr = [createStartTime, endTime]
        return createArr
      },
      createTimeChange (value) {
        if (!value) {
          this.chatForm.createTime = this.chatCreateTimeReset()
        }
      },
      closeBigImage () {
        this.bigImage.bigImageShow = false
        this.bigImage.url = ''
      },
      // 查看日志
      look (_id) {
        this.paginationRecord.currentPage = 1
        this.countRecord = 0
        this.totalPageRecord = 0
        this.queryRecordWebchatSessionLog(_id, 1)
      },
      queryRecordWebchatSessionLog (_id, page) {
        this.currentId = _id
        this.title = this.$t('qualityCheck.onlineWebchatLog')
        this.listenpp = this.$t('qualityCheck.checkPeople')
        this.listenTime = this.$t('qualityCheck.checkTime1')
        this.$store.dispatch('queryRecordWebchatSessionLog', {'sessionId': _id, 'page': page, 'pageSize': 10}).then(() => {
          this.recordList = this.$store.state.qualityCheck.recordList.list
          this.countRecord = this.$store.state.qualityCheck.recordList.count
          this.totalPageRecord = Math.ceil(this.$store.state.qualityCheck.recordList.count / 10) || 0
          this.isShow = true
        })
      },
      // 获取所有质检条数
      getAllCount () {
        this.allCount = 0
        let form = this.qu
        const more = false
        this.$store.dispatch('webchatSearch1', form).then((res) => {
          this.allCount = res.count
          let type = 'qc'
          this.$store.commit('qualityCheck/SET_QUAL_MORE', {more, type})
        })
      },
      // 低于五条请求数据
      getMoreQualityCheckCallSheet () {
        this.chatForm.menuId = 'autoqc_query'
        delete this.chatForm.cdrId
        if (this.chatForm.beginTime && this.chatForm.beginTime[0] !== null) {
          this.chatForm.beginTimeBegin = getDateTime(this.chatForm.beginTime[0])
        }
        if (this.chatForm.beginTime && this.chatForm.beginTime[1] !== null) {
          this.chatForm.beginTimeEnd = getDateTime(this.chatForm.beginTime[1])
        }
        if (this.chatForm.beginTimeEnd === '' && this.chatForm.beginTimeBegin === '') {
          this.chatForm.beginTime = ''
        }
        if (this.chatForm.createTime) {
          if (typeof this.chatForm.createTime[0] === 'object') {
            this.chatForm.createTimeBegin = getDateTime(this.chatForm.createTime[0])
          } else {
            this.chatForm.createTimeBegin = this.chatForm.createTime[0] || ''
          }
          if (typeof this.chatForm.createTime[1] === 'object') {
            this.chatForm.createTimeEnd = getDateTime(this.chatForm.createTime[1])
          } else {
            this.chatForm.createTimeEnd = this.chatForm.createTime[1] || ''
          }
        }
        this.chatForm.pageSize = 10
        let form = deepClone(this.chatForm)
//          createTime属性查询的时候用不到，所以不传
        delete form.createTime
        this.$store.dispatch('getMoreQualityCheckCallSheet', {data: form, tempList: this.tempList, type: 'webchat', searchType: 'autoqc'})
      },
      // 组件评分传上来的事件
      handle (data) {
        this.currentIndex = 0
        for (let i = 0; i < this.tempList.length; i++) {
          if (this.tempList[i]._id === data._id) {
            this.currentIndex = i
            break
          }
        }
        if (data.REPEAT_CALL) {
          data.repeatCall = data.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          data.repeatCall = '--'
        }
        var num = this.tempList.length - this.currentIndex
        if (num < 5) {
          setTimeout(this.getMoreQualityCheckCallSheet, 1000)
        }
        this.webchatDialogShow = true
        let self = this
        this.$store.dispatch('recordWebchatSessionLog', {_id: data._id})
        this.$store.dispatch('queryBusiness', {linkWebchat: data._id, sid: data.sid}).then((response) => {
          if (response && response.length > 0) {
            data.busHistory = [response[0]]
          } else {
            data.busHistory = []
          }
          self.currentItemWebchat = data
        })
        if (data.finishKey) {
          data.finishReasonTitle = this.finishOptions[data.finishKey] || ''
        } else {
          data.finishReasonTitle = ''
        }
        self.currentItem = data
        self.webChatIsShow = true
        bus.$emit('webchatScoreFetch')
      },
      // 配置表头
      setHeaderConfig () {
        this.$store.dispatch('getReportTableHeader', 'quality_webchat_table_title').then((res) => {
          this.headOptions = res
          this.tableConfigType = 'quality_webchat_table_title'
          this.isShowTableConfig = !this.isShowTableConfig
        })
      },
      closeTableConfig (data) {
        this.isShowTableConfig = false
        if (data === 'save') {
          this.query()
        }
      },
      // 关闭弹窗
      off () {
        let play = document.getElementById('quality-autoplay_' + this.flagId)
        if (play) {
          play.pause()
        }
        this.webchatDialogShow = false
        if (this.isSave === true) {
          this.query()
        }
      },
      // 质检翻页
      turnPage (pageNum) {
        if (this.$store.state.qualityCheck.intelSearchList.type === 'qualityWebchat') {
          this.allCount = 0
          this.pagination.currentPage = pageNum
          //   翻页  morePage
          this.chatForm.page = pageNum
          //   翻页  morePage
          let morePage = 1
          if (pageNum > 1) {
            morePage = Math.floor(pageNum / this.chatPages + 1)
          }
          this.chatForm.morePage = morePage
          this.getQualityCheckWebchatSession()
        }
      },
      // 查看日志翻页
      turnPageRecord (pageNum) {
        this.paginationRecord.currentPage = pageNum
        this.queryRecordWebchatSessionLog(this.currentId, pageNum)
      },
      // 取消全选
      cancelChoose () {
        this.$refs.qualityTable.cancleChoose()
        this.checked = false
      },
      checkData (arr) {
        console.log(arr)
        this.arrChooseTab = arr
        this.checked = false
      },
      queryList () {
        this.pagination.currentPage = 1
        this.chatForm.page = 1
        this.chatForm.morePage = 1
        this.query()
      },
      // 查询数据
      query () {
        this.getQualityCheckWebchatSession()
        this.isSave = false
      },
      getQualityCheckWebchatSession () {
        this.chatForm.menuId = 'autoqc_query'
        if (this.chatForm.beginTime && this.chatForm.beginTime[0] !== null) {
          this.chatForm.beginTimeBegin = getDateTime(this.chatForm.beginTime[0])
        }
        if (this.chatForm.beginTime && this.chatForm.beginTime[1] !== null) {
          this.chatForm.beginTimeEnd = getDateTime(this.chatForm.beginTime[1])
        }
        if (this.chatForm.beginTimeEnd === '' && this.chatForm.beginTimeBegin === '') {
          this.chatForm.beginTime = ''
        }
        if (this.chatForm.createTime) {
          if (typeof this.chatForm.createTime[0] === 'object') {
            this.chatForm.createTimeBegin = getDateTime(this.chatForm.createTime[0])
          } else {
            this.chatForm.createTimeBegin = this.chatForm.createTime[0] || ''
          }
          if (typeof this.chatForm.createTime[1] === 'object') {
            this.chatForm.createTimeEnd = getDateTime(this.chatForm.createTime[1])
          } else {
            this.chatForm.createTimeEnd = this.chatForm.createTime[1] || ''
          }
        }
        let finishArr = this.activeFinish
        if (finishArr && finishArr.length > 0) {
          for (let i = 0; i < finishArr.length; i++) {
            finishArr[i] = finishArr[i].split('__')[0]
            if (finishArr[i] === '') {
              this.chatForm.finishKey = ''
            }
            if (finishArr[i] === 'add_black') {
              this.chatForm.finishKey = 'add_black'
            }
          }
        }
        this.chatForm.finishKey = finishArr[finishArr.length - 1]
        this.chatForm.pageSize = 10
        let _qu = deepClone(this.chatForm)
        _qu.queryCount = true
        this.qu = _qu
        this.allCount = 0
        let data = deepClone(this.chatForm)
        delete data.beginTime
        delete data.createTime
        data.searchType = 'autoqc'
        if(!data._id){
          delete data._id
        }
        if(!data.sName){
          delete data.sName
        }
        this.$store.dispatch('webchatSearch', data).then((res) => {
          if (data.page === 1 && this.count) {
            this.chatPages = this.count / 10
          }
          const list = res.list || []
          if (list.length === 0) {
            if (res.more) {
              this.turnPage(1)
            } else {
              if (!res.count) {
                // 第一页且count为0是不再发请求
                this.pagination.currentPage = 1
                this.chatForm.morePage = 1
              } else {
                let page = Math.ceil(res.count / data.pageSize)
                this.chatForm.page = page
                this.pagination.currentPage = page
                this.turnPage(page)
                return false
              }
            }
          }
          this.tableData = list
          this.tableDataHeader = res.tableHeader
        })
      },
      isFold (bool) {
        this.isShowCon = bool
      },
      timeChange (value) {
        if (!value) {
          this.chatForm.beginTimeBegin = ''
          this.chatForm.beginTimeEnd = ''
          this.chatForm.begin = ''
        }
      }
    },
    components: {
      affix,
      BigImage,
      qcDialog,
      headerOption,
      Pagination,
      webchatGrade,
      BaseTable,
      AgentTree
    },
    computed: {
      count () {
        if (this.$store.state.qualityCheck.intelSearchList.qcMore) {
          this.moreNorFlag = true
        } else {
          this.moreNorFlag = false
        }
        return this.$store.state.qualityCheck.intelSearchList.qcCount
      },
      tempList () {
        return this.$store.state.qualityCheck.tempListAuto
      },
      totalPage () {
        return Math.ceil(this.$store.state.qualityCheck.intelSearchList.qcCount / 10) || 0
      },
      //坐席展示数据
      followedWebchatAgents () {
        let agents = this.chatForm.user || []
        let agentsAll = this.$store.getters.agents || {}
        return agents.map((item) => {
          return {_id: item, label: agentsAll[item].displayName}
        })
      },
    },
    beforeMount () {
      this.chatForm.createTime = this.chatCreateTimeReset()
      this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
        console.log(res)
        let agents = scopeAgents('qc', res)
        this.agentList = agents
      })
      this.$store.dispatch('getCache', {type: 'channelDic'}).then((dics) => {
        for (var i = 0; i < dics.length; i++) {
          let obj = dics[i]
          if (obj.type === 'webchatCSR') {
            this.appraiseList = obj.options || []
            break
          }
        }
      })
      this.$store.dispatch('getCache', {type: 'mailQueues'}).then((res) => {
        this.webchatQueueList = res
      })
      this.$store.dispatch('getCache', {type: 'channelDic'}).then((dics) => {
        let _dics = []
        for (var i = 0; i < dics.length; i++) {
          let obj = dics[i]
          if (obj.type === 'webchat') {
            _dics = obj.options || []
            break
          }
        }
        this.finishOptions = initFinishName(_dics, {})
        let finishKeys = []
        updateAllOptions(_dics, {Arr: this.sessionOptions})
        this.closeOptions = [
          {label: this.$t('webchat.webchatAll'), value: ''}, ...this.sessionOptions,
          {label: this.$t('webchat.addBlack'), value: 'add_black'}
        ]
      })
      let data = {
        page: 1,
        pageSize: 200
      }
      this.$store.dispatch('getMarkRuleListConfig', data).then(res => {
        if (res.success) {
          res.data = res.data.filter((item) => {
            return item.type === 'webchat' && item.isEnable
          })
          this.ruleRender = deepClone(res.data)
        }
      })
      let data1 = {
        isEnable: true
      }
      this.$store.dispatch('getRuleLessList', data1).then((res) => {
        if (res.success) {
          // 过滤下类型
          res.data = res.data.filter((item) => {
            return item.type === 'webchat'
          })
          for (var i = 0; i < res.data.length; i++) {
            this.Qclists.push({
              name: res.data[i].name,
              value: res.data[i]._id
            })
          }
        }
      })
      let startDate = new Date()
      let endDate = new Date()
      startDate.setTime(startDate.getTime() - 3600 * 1000 * 24 * 30)
      this.chatForm.beginTime = [startDate, endDate]
      this.chatForm.page = 1
      this.chatForm.morePage = 1
      this.query()
    },
    activated () {
      this.query()
    },
    watch: {
      refreshNum () {
//        this.query()
      }
    }
  }
</script>
<style lang="stylus" scoped>
@import "../../../../assets/common.styl"
  .qc_webchat_Quality
    .ui-affix
      padding-bottom 2px
    .wrapper_table
      padding-bottom 30px
      .search-pagination
        position: relative
        .page_mask
          position: absolute
          width 100%
          height 100%
          cursor: no-drop
      .choose
        font-size 14px
        .el-checkbox
          margin-left 12px
      .not_choose
        color $c-main
        cursor: pointer
        margin-left 14px
    .sub
      text-align right
      margin-bottom 10px
    .demo-form-inline
      .el-form-item
        width 100%
        height 100%
        .el-select, .el-date-editor, .el-input
          width 100%
          height 100%
    .follow-agent-wrap
      float left
      width: calc(100% - 14px)
      cursor pointer
      border-radius 5px
      border 1px solid #dcdfe6
      padding 8px 8px 6px 4px
      margin-top 6px
      overflow hidden
    .follow-common
      float left
      position relative
      line-height 24px
      background-color #7ab8f3
      margin 0 0 10px 10px
      padding 0 10px
      color #fff
      border-radius 4px
    .follow-agent-add
      cursor pointer
    .el-icon-close
      font-size 12px
    .follow-agent
      color #fff
      margin 0 0 8px 8px
      font-size 12px
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 12px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color #0f99fc
        border-radius 50%
        border 1px solid #cce6ff
        cursor pointer
    .follow-agent-wrap-btn
      display block !important
      line-height 0px
      float right
      cursor pointer
      color $c-main
</style>
